#include<iostream>
#include<mysql/mysql.h>

const std::string host="127.0.0.1";
const std::string user="http_test";
const std::string pwd="12345678";
const std::string db="http_test";
const unsigned int port=3306;

int main()
{
    std::cout<<mysql_get_client_info()<<std::endl;
    //1.初始化mysql句柄
    MYSQL* my=mysql_init(nullptr);//默认设置为nullptr
    if(my==nullptr)
    {
        std::cerr<<"init mysql error"<<std::endl;
        return 1;
    }
    mysql_set_character_set(my,"utf8");
    //2.连接数据库
    if(mysql_real_connect(my,host.c_str(),user.c_str(),pwd.c_str(),db.c_str(),port,nullptr,0)==nullptr)
    {
        std::cerr<<"mysql connect error"<<std::endl;
    }
    std::cout<<"mysql connect success"<<std::endl;
    //3.构建mysql语句
    // std::string name,password;
    // std::cin>>name>>password;
    // std::string sql="insert into user (name,password) values ('"+name+"','"+password+"')";
    // std::cout<<"excute: "<<sql<<std::endl;
    std::string sql="select * from user";
    //4.执行sql命令
    if(0!=mysql_query(my,sql.c_str()))
    {
        std::cerr<<sql<<" excute error"<<std::endl;
        return 2;
    }
    std::cout<<sql<<" excute success"<<std::endl;
    //5.select拿出数据-需要先执行查询sql语句
    MYSQL_RES* res=mysql_store_result(my);
    int rows=mysql_num_rows(res);
    int cols=mysql_num_fields(res);
    std::cout<<"rows: "<<rows<<" cols: "<<cols<<std::endl;
    MYSQL_FIELD* field=mysql_fetch_fields(res);
    for(int i=0;i<cols;i++)
    {
        std::cout<<field[i].name<<"\t";
    }
    std::cout<<std::endl;
    MYSQL_ROW row;
    for(int i=0;i<rows;i++)
    {
        row=mysql_fetch_row(res);
        for(int j=0;j<cols;j++)
        {
            std::cout<<row[j]<<"\t";
        }
        std::cout<<std::endl;
    }
    free(res);
    mysql_close(my);
    return 0;
}